from util.TokenHelper import TokenHelper
import pandas as pd
from dao.UserDao import UserDao
from util import CommonHelper
from Static import Static
from StatusCode import StatusCode
from util import Logger


class UserService:
    def initDB(self):
        dao = UserDao()
        df1 = dao.getAllUsers()
        if df1.shape[0] == 0:
            admin = {
                "username": Static.SYSTEM_SUPER_NAME,
                "nickname": Static.SYSTEM_SUPER_NICK,
                "password": CommonHelper.md5(Static.SYSTEM_SUPER_PWD),
                "phone": Static.SYSTEM_SUPER_PHONE,
                "gender": Static.SYSTEM_SUPER_GENDER,
                "dept_id": 1,
                "state": "1",
                "role": Static.ROLE_ADMIN,
            }
            df2 = pd.DataFrame(data=[admin], columns=admin.keys())
            dao.importUsers(df2)

    def getInfo(self, token):
        tokenHelper = TokenHelper()
        userName = tokenHelper.verifyToken(token)
        df = UserDao().getUserInfoByUserName(userName)
        return df

    def getUserProfile(self, token):
        return self.getInfo(token)

    def getUserRole(self, token):
        role = Static.ROLE_NORMAL
        df = self.getInfo(token)
        if df.shape[0] > 0:
            role = df.iloc[0]["role"]
        return role

    def generateJwtToken(self, username):
        tokenHelper = TokenHelper()
        token = tokenHelper.generateJwtToken(username)
        return token

    def login(self, username, pwd):
        uDao = UserDao()
        pwd = CommonHelper.md5(pwd)
        return uDao.verifyUser(username, pwd)

    def getUserList(self, json_data):
        name = json_data.get("name", "").strip()
        dept = json_data.get("dept", "").strip()
        df = UserDao().queryUsers(name, dept)
        return df

    def getUserInfo(self, json_data):
        try:
            userId = json_data.get("userId", -1)
            df = UserDao().getUserInfo(userId)
            return df
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL

    def deleteUser(self, json_data):
        try:
            userId = json_data.get("userId", -1)
            if userId == -1:
                return StatusCode.RESPONSE_FAIL
            UserDao().deleteUser(userId)
            return StatusCode.RESPONSE_SUCCESS
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL

    def addUser(self, json_data):
        try:
            dao = UserDao()
            Logger.logger(json_data)
            user = json_data.get("username", "").strip()
            if dao.getUserInfoByUserName(user).shape[0] > 0:
                return StatusCode.RESPONSE_EXIST
            pwd = json_data.get("password", "").strip()
            if pwd == "":
                pwd = Static.USER_DEFAULT_PWD
            pwd = CommonHelper.md5(pwd)
            userItem = {
                "username": user,
                "password": pwd,
                "nickname": json_data.get("nickname", "").strip(),
                "gender": json_data.get("gender", "").strip(),
                "phone": json_data.get("phone", "").strip(),
                "dept_id": json_data.get("dept_id", 1),
                "role": json_data.get("role", "").strip(),
            }
            df = pd.DataFrame(data=[userItem], columns=userItem.keys())
            dao.importUsers(df)
            return StatusCode.RESPONSE_SUCCESS
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL

    def updateUser(self, json_data):
        try:
            dao = UserDao()
            id = json_data.get("id", -1)
            if id == -1:
                return StatusCode.RESPONSE_FAIL
            user = json_data.get("username", "").strip()
            nick = json_data.get("nickname", "").strip()
            phone = json_data.get("phone", "").strip()
            gender = json_data.get("gender", "").strip()
            dept_id = json_data.get("dept_id", 1)
            role = json_data.get("role", "").strip()
            dao.updateUser(id, user, nick, phone, gender, dept_id, role)
            return StatusCode.RESPONSE_SUCCESS
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL

    # 重置密码
    def resetPwd(self, json_data):
        try:
            userId = json_data.get("userId", -1)
            if userId == -1:
                return StatusCode.RESPONSE_FAIL
            pwd = CommonHelper.md5(Static.USER_DEFAULT_PWD)
            UserDao().resetPwd(userId, pwd)
            return StatusCode.RESPONSE_SUCCESS
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL

    # 状态切换
    def changeUserState(self, json_data):
        try:
            userId = json_data.get("userId", -1)
            if userId == -1:
                return StatusCode.RESPONSE_FAIL
            state = json_data.get("state", "1").strip()
            dao = UserDao()
            dao.changeUserState(userId, state)
            return StatusCode.RESPONSE_SUCCESS
        except Exception as e:
            print(e)
            return StatusCode.RESPONSE_FAIL
